package utils
{
	import flash.events.Event;
	import flash.utils.getTimer;
	
	import modules.GameDispatcher;
	import modules.GameEvent;

	public class CycleFunction
	{
		private static var instancs:CycleFunction;

		private namespace foo;

		public static function init():void
		{
			logger("初始化周期函数管理类");
			instancs = new CycleFunction();
		}

		public function CycleFunction()
		{
			UIAllRefer.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);

			addListeners();
		}

		private var functionObjectList:Array = [];

		private function onEnterFrame(event:Event):void
		{
			var nowTime:int = getTimer();
			for each (var functionObject:Object in functionObjectList)
			{
				if (nowTime - functionObject.preTime > functionObject.cycle)
				{
					//判断是否需要执行
					var need:Boolean = functionObject.need ? functionObject.need() : true;
					if (need)
					{
						functionObject.run();
						functionObject.preTime = nowTime;
					}
				}
			}
		}

		private function get dispatcher():GameDispatcher
		{
			return GameDispatcher.instance;
		}

		/**
		 * 添加侦听器
		 */
		private function addListeners():void
		{
			dispatcher.addEventListener(GameEvent.ADD_CYCLE_FUNCTION, onAddCycleFuction);
		}

		private function onAddCycleFuction(event:GameEvent):void
		{
			var functionObject:Object = event.data;
			addFunction(functionObject);
		}

		private function addFunction(functionObject:Object):void
		{
			deleteFunction(functionObject.name);
			$addFunction(functionObject);
		}

		private function $addFunction(functionObject:Object):void
		{
			functionObjectList.push(functionObject);
		}

		private function deleteFunction(functionName:String):void
		{
			var length:int = functionObjectList.length;
			for (var i:int = length - 1; i >= 0; i--)
			{
				var functionObject:Object = functionObjectList[i];
				if (functionObject.name == functionName)
				{
					functionObjectList.splice(i, 1);
				}
			}
		}

	}
}
